var express = require('express');
var router = express.Router();
require('./../utils/util')
var User = require('./../models/user')
/* GET users listing. */
router.post('/', function(req, res, next) {
  res.send('respond with a resource');
});

/* GET users listing. */
router.post('/login', function(req, res, next) {
  var params = {
    userName: req.body.userName,
    userPwd: req.body.userPwd
  }
  User.findOne(params,function (err,doc) {
    if (err) {
      res.json({
        status: 0,
        msg: err.message
      })
    }else {
      if (doc) {
        res.cookie("userId",doc.userId,{
          path: '/',
          maxAge: 1000*60*60
        })
        res.cookie("userName",doc.userName,{
          path: '/',
          maxAge: 1000*60*60
        })
        req.session.user = doc
        res.json({
          status: 1,
          msg: '',
          result: {
            userName: doc.userName
          }
        })
      }else {
        res.json({
          status: 0,
          msg: "账号或密码为空"
        })
      }
    }
  })
});

//登出接口
router.post("/logout",function (req,res,next) {
  res.cookie("userId","",{
    path:"/",
    maxAge:-1
  })
  res.json({
    status:"1",
    msg:'',
    result: ''
  })
})

//校验登录
router.post("/checkLogin", function (req, res, next) {
  if (req.cookies.userId) {
    res.json({
      status: '1',
      msg: '',
      result: {
        userName: req.cookies.userName
      }
    })
  }else {
    res.json({
      status: '0',
      msg: '',
      result: '未登录'
    })
  }
})

//获取用户的购物车列表
router.post("/carList",(req,res,next)=>{
  var userId = req.cookies.userId
  User.findOne({userId:userId},(err,doc)=>{
    if (err) {
      res.json({
        status: '0',
        msg: err.message,
        result: ''
      })
    }else {
      res.json({
        status: '1',
        msg: '',
        result: {
          list: doc.cartList
        }
      })
    }
  })
})

//查询当前用户的购物车数量
router.post("/getCartCount",(req,res,next)=>{
  if (req.cookies && req.cookies.userId){
    var userId = req.cookies.userId
    User.findOne({
      userId: userId
    },(err,userDoc)=>{
      if (err){
        res.json({
          status: 0,
          msg: err.message,
          result: ''
        })
      } else {
        var carList = userDoc.cartList
        let cartCount = 0
        carList.forEach((item)=>{
          cartCount += parseInt(item.productNum)
        })
        res.json({
          status: 1,
          msg: '',
          result: cartCount
        })
      }
    })
  }
})


//删除用户的购物车商品
router.post("/carList/deleteGoods",(req,res,next)=>{
  var userId = req.cookies.userId
  var productId = req.body.productId

  User.update({userId:userId},{
    $pull:{
      'cartList':{
        'productId':productId
      }
    }},(err,doc)=>{
    if (err) {
      res.json({
        status: '0',
        msg: err.message,
        result: ''
      })
    }else {
      res.json({
        status: '1',
        msg: '',
        result: ''
      })
    }
  })

  // User.remove({userId:userId,productId:productId},(err,doc)=>{
  //
  // })
})

//修改购物车商品
router.post("/carList/edit",(req,res,next)=>{
  var userId = req.cookies.userId,
      productId = req.body.productId,
      productNum = req.body.productNum,
      checked = req.body.checked
  User.update({"userId":userId,"cartList.productId":productId},{
    "cartList.$.productNum":productNum,
    "cartList.$.checked":checked,
  },(err,doc)=>{
    if (err) {
      res.json({
        status: '0',
        msg: err.message,
        result: ''
      })
    }else {
      res.json({
        status: '1',
        msg: '',
        result: 'suc'
      })
    }
  })
})

//选中全部
router.post("/carList/editCheckAll",(req,res,next)=>{
  var userId = req.cookies.userId,
      checkAll = req.body.checkAll
  User.findOne({userId:userId},(err,user)=>{
    if (err) {
      res.json({
        status: '0',
        msg: err.message,
        result: ''
      })
    }else {
      if (user) {
        user.cartList.forEach((item)=>{
          item.checked = checkAll
        })
      }
      user.save((err,doc)=>{
        if (err) {
          res.json({
            status: '0',
            msg: err.message,
            result: ''
          })
        }else {
          res.json({
            status: '1',
            msg: '',
            result: 'suc'
          })
        }
      })
    }
  })
})

//获取用户地址列表
router.post("/addressList",(req,res,next)=>{
  var userId = req.cookies.userId
  User.findOne({
    userId:userId
  },(err,userDoc)=>{
    if(err) {
      res.json({
        status: 0,
        msg: err.message
      })
    }else {
      res.json({
        status: 1,
        msg: '',
        result:{
          list: userDoc.addressList
        }
      })
    }
  })
})

//设置默认地址
router.post("/address/setDefault",(req,res,next)=>{
  var userId = req.cookies.userId,
      addressId = req.body.addressId
  if (!addressId) {
    res.json({
      status: 1003,
      msg: '',
      result: ''
    })
  }
  User.findOne({
    userId:userId
  },(err,userDoc)=>{
    if(err) {
      res.json({
        status: 0,
        msg: err.message,
        result: ''
      })
    }else {
      var addressList = userDoc.addressList
      addressList.forEach((item)=>{
        if (addressId == item.addressId) {
          item.isDefault = true
        }else {
          item.isDefault = false
        }
      })
      userDoc.save((err,doc)=>{
        if (err) {
          res.json({
            status: 0,
            msg: err.message,
            result: ''
          })
        } else {
          res.json({
            status: 1,
            msg: '',
            result: 'suc'
          })
        }
      })
    }
  })
})

//删除选中地址
router.post("/address/delete",(req,res,next)=>{
  var userId = req.cookies.userId,
      addressId = req.body.addressId
  User.update({userId: userId},{
    $pull:{
      addressList:{
        addressId:addressId
      }
    }},(err)=>{
      if (err) {
        res.json({
          status: 0,
          msg: err.message,
          result: ''
        })
      } else {
        res.json({
          status: 1,
          msg: '',
          result: 'suc'
        })
      }
  })
})

//生成购物订单
router.post('/payment',(req,res,next)=>{
  var userId = req.cookies.userId,
      orderTotal = req.body.orderTotal,
      addressId = req.body.addressId
  User.findOne({
    userId:userId
  },(err,userDoc)=>{
    if (err) {
      res.json({
        status: 0,
        msg: err.message,
        result: ''
      })
    } else {
      var address = '',goodsList = []
      userDoc.addressList.forEach((item)=>{
        if (item.addressId == addressId) {
          address = item
        }
      })
      //获取购物车的购买商品
      userDoc.cartList.forEach((item)=>{
        if (item.checked){
          goodsList.push(item)
        }
      })

      var platform = '622'
      var r1 = Math.floor(Math.random()*10)
      var r2 = Math.floor(Math.random()*10)
      var sysDate = new Date().Format('yyyyMMddhhmmss')
      var createDate = new Date().Format('yyyy-MM-dd hh:mm:ss')
      var orderId = platform+r1+sysDate+r2

      var order = {
        orderId: orderId,
        orderTotal: orderTotal,
        addressInfo: address,
        goodsList: goodsList,
        orderStatus: 1,
        createDate: createDate
      }

      userDoc.orderList.push(order)

      userDoc.save((err,doc)=>{
        console.log(`err is ${err} and doc is ${doc}`)
        if (err) {
          res.json({
            status: 0,
            msg: err.message,
            result: ''
          })
        } else {
          res.json({
            status: 1,
            msg: '',
            result: {
              orderId: order.orderId,
              orderTotal: order.orderTotal
            }
          })
        }
      })
    }
  })
})

//根据orderId查询订单信息
router.post("/order/detail",(req,res,next)=>{
  var userId = req.cookies.userId,
      orderId = req.body.orderId
  User.findOne({
    userId:userId
  },(err,userDoc)=>{
    console.log(`user is ${userDoc}`)
    if (err) {
      res.json({
        status: 0,
        msg: err.message,
        result: ''
      })
    } else {
      var orderList = userDoc.orderList
      var orderItem = null
      if (orderList.length > 0) {
        orderList.forEach((item)=>{
          if (item.orderId == orderId){
            orderItem = item
          }
        })
        res.json({
          status: 1,
          msg: '',
          result: orderItem
        })
      }else {
        res.json({
          status: 0,
          msg: '无此订单',
          result: ''
        })
      }
    }
  })
})

module.exports = router;
